import { createSlice } from '@reduxjs/toolkit';
import { get_menus as getMenus } from '../../services/login';

// 防御：确保 window.APP_CONFIG 存在，否则赋默认空对象
const APP_CONFIG = window.APP_CONFIG || {}; 

const configSlice = createSlice({
  name: "config",
  initialState: {
    // 修复：处理 sessionStorage 为 null 的情况，给默认值
    defaultOpenKeys: [
      sessionStorage.getItem('defaultOpenKeys') || APP_CONFIG.defaultOpenKeys || ''
    ],
    defaultSelectedKeys: [
      sessionStorage.getItem('defaultSelectedKeys') || APP_CONFIG.home || '/'
    ],
    collapsed: false,
    selected_menu: {},
  },
  reducers: {
    set_defaultOpenKeys(state, action) {
      state.defaultOpenKeys = [action.payload];
      sessionStorage.setItem('defaultOpenKeys', action.payload);
    },
    set_defaultSelectedKeys(state, action) {
      state.defaultSelectedKeys = [action.payload];
      sessionStorage.setItem('defaultSelectedKeys', action.payload);
    },
    set_selected_menu(state, action) {
      // 防御：确保 payload 是合法 JSON（若 action.payload 本身是对象，可直接赋值）
      try {
        state.selected_menu = JSON.parse(action.payload);
      } catch (error) {
        state.selected_menu = action.payload; // 本身是对象时直接存
      }
    },
    toggleCollapsed(state) {
      state.collapsed = !state.collapsed;
    },
    set_collapsed(state, action) {
      state.collapsed = action.payload;
    }
  }
});

// 修复：导出的 action 名称与 reducers 一致，原代码里的 set_selected_key 是拼写错误
export const { 
  set_defaultOpenKeys, 
  set_defaultSelectedKeys, 
  set_selected_menu, 
  toggleCollapsed, 
  set_collapsed,
  set_menu_loading 
} = configSlice.actions;

export default configSlice.reducer;